﻿using Jint;
using Jint.Native;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WorkFlowCore.Conditions;
using WorkFlowCore.Plugins;

namespace WorkFlowCore.Framework.Conditions
{
    [Condition("自定义 Javascript 条件处理器（基于 JavaScriptServices ）", "通过 js 方法解析条件， 具体传参需根据插件配置决定")]
    [PluginDescription("函数代码：function canAccept(input){/*中间这部分自定义js代码，目的是为了解析参数 */  return true;},input 为 json 格式（参考 ConditionInput） {Expression:string 表达式,WorkTask:object 当前流程实例,CurrentWorkStep:object 当前审批步骤}")]
    [PluginDescription("返回：函数返回一个 bool 值，表示是否通过")]
    public class DefaultJavascriptCondition : ICondition, IConfigurable
    {
        public bool CanAccept(ConditionInput input)
        {
            try
            {
                var engine = new Engine(options =>
                {
                    options.Strict(false);
                });

                var data = (object)JsonConvert.DeserializeObject<dynamic>(input.WorkTask.FormData);
                var step = (object)JsonConvert.DeserializeObject<dynamic>(input.CurrentWorkStep.FormData??"{}");
                var canAccept = engine
                    .SetValue("data", data)
                    .SetValue("step", step)
                    //.Execute(configureContext.OriginalParameters.Replace("{Expression}", input.Expression))
                    .Execute("function canAccept(){return {Expression};}".Replace("{Expression}", input.Expression))
                    .GetValue("canAccept");

                var result = canAccept.Invoke("");

                return result.AsBoolean();
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        ConfigureContext configureContext;
        public Task Configure(ConfigureContext configureContext)
        {
            this.configureContext = configureContext;
            return Task.CompletedTask;
        }
    }
}
